import logging
import sys
from pathlib import Path


class GlobalLogger:
    _instance = None
    _initialized = False

    @classmethod
    def initialize(cls, log_file="ot-slayer.log", console_output=True):
        if cls._initialized:
            return logging.getLogger()

        # 确保单例模式
        if cls._instance is None:
            cls._instance = cls.__new__(cls)
            cls._instance.__setup_logger(log_file, console_output)
            cls._initialized = True
        return cls._instance.logger

    @staticmethod
    def get_logger():
        if not GlobalLogger._initialized:
            # 未初始化时提供默认配置
            return GlobalLogger.initialize()
        return logging.getLogger()

    def __setup_logger(self, log_file, console_output):
        """配置全局日志系统"""
        logger = logging.getLogger()
        logger.setLevel(logging.DEBUG)

        # 清除任何已存在的处理程序
        for handler in logger.handlers[:]:
            logger.removeHandler(handler)

        # 创建格式化器
        formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")

        # 文件处理程序（如果指定了日志文件）
        if log_file:
            log_path = Path(log_file)
            log_path.parent.mkdir(parents=True, exist_ok=True)
            file_handler = logging.FileHandler(log_file, encoding="utf-8")
            file_handler.setFormatter(formatter)
            file_handler.setLevel(logging.DEBUG)
            logger.addHandler(file_handler)

        # 控制台处理程序（如果启用）
        if console_output or not log_file:
            console_handler = logging.StreamHandler(sys.stdout)
            console_handler.setFormatter(formatter)
            console_handler.setLevel(logging.INFO)
            logger.addHandler(console_handler)

        self.logger = logger
        logger.info("===== 日志系统初始化完成 =====")


# 提供全局访问的便捷方法
def setup_logging(log_file=None, console_output=True):
    """初始化全局日志系统，应该在应用启动时调用一次"""
    return GlobalLogger.initialize(log_file, console_output)


def get_logger():
    """在任何地方获取全局日志实例"""
    return GlobalLogger.get_logger()
